package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.pojo.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*if (request.getRemoteAddr().startsWith("192.168")) {
            response.setContentType("text/html;charset=utf-8");
            log.info("{}",request.getRemoteAddr());
            response.getWriter().write("撒~~~~~~~~b");
            return false;
        }*/

        Employee employee = (Employee) request.getSession().getAttribute("employee");
        //判断后端是否登录
        if (employee != null) {
            BaseContext.setCurrentId(employee.getId());
            return true;

        }
        //判断移动端
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId!=null){
            BaseContext.setCurrentId(userId);
            return true;
        }
        String json = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(json);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
